package com.netty.cn.rpc.selfmessage;

import com.netty.cn.rpc.selfmessage.core.MyMessage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class MyClientHandler extends SimpleChannelInboundHandler<MyMessage> {
 
 
    /**
     * 当客户端连接到服务端是触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	System.out.println("连接服务端 "+ctx.channel().remoteAddress()+" 成功");
    	
        String msg="你好，我是张asdfasdfsadfwerwerwerwerewrewrewrewr三。";
        for (int i=0;i<20;i++){//多次发送，校验是否解决了拆包粘包
            MyMessage message=new MyMessage();
            message.setContent(msg.getBytes(CharsetUtil.UTF_8));
            message.setLen(msg.getBytes(CharsetUtil.UTF_8).length);
            ctx.writeAndFlush(message);
        }
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyMessage myMessage) throws Exception {
    	System.out.println("client 接收到信息:"+new String(myMessage.getContent()).toString());
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

}
